<?php

namespace app\agent\controller;

use app\common\Common;
use app\common\BaseHelper;

use think\Exception;

class Profile extends Base
{

    public function _initialize()
    {

        $this->exceptAction = ['save'];
        parent::_initialize();
    }

    public function index(){
        $info = $this->admin;
        $this->assign('info', $info);

        return $this->view->fetch();
    }

    public function save(){
        $request = $this->request;
        if($this->request->isAjax()) {
            $model = model('Agentuser');
            $params = $this->request->param();

            if(BaseHelper::passwordEncrypt($params['ori_password']) != $this->admin->password){
                return json(['status' => 0, 'msg' => '密码不正确！']);
            }
            // Update data
            $data['id'] = $this->admin->id;
            $data['loginName'] = $params['loginName'];
            $data['phone'] = $params['phone'];
            if($params['password']){
                $data['password'] = BaseHelper::passwordEncrypt($params['password']);
            }

            try {
                $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

                if($result !== false) {
                    $agentInfo = $model->where(['id' => $this->admin->id])->find();
                    session('AGENT', $agentInfo);
                    // 写入日志
                    $logInfo = $this->admin->loginName . '更新了个人中心数据。';
                    common::agentLog($request, $logInfo);

                    return json(['status' => 1, 'msg' => '保存成功！']);
                } else {
                    return json(['status' => 0, 'msg' => '保存失败！']);
                }
            } catch (Exception $e) {
                return json(['status' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 0, 'msg' => '请求方式不正确！']);
        }
    }

}